package myJs.member.loadSample

import myJs.CpLayer
import myJs.Implicits._
import myJs.cps.{ImageSelectCp, PureInputCp}
import myJs.myPkg.jquery.$
import myJs.myPkg.{MyFetch, SwalOptions, layer, swal}
import myJs.tool.Tool
import org.scalajs.dom.html
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.React
import slinky.web.html._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON


/**
 * Created by yz on 21/1/2022
 */
@react object Cp {

  val curPage = LoadSample
  type Props = Unit

  val component = FunctionalComponent[Props] { props =>

    val (idV, setIdV) = useState("")
    val (images, setImages) = useState(List.empty[String])

    val formRef = React.createRef[html.Form]

    object FTool {

      def add = () => {
        val formJq = $(formRef.current)
        val bv = formJq.bv
        bv.validate()
        val valid = bv.isValid()
        if (valid) {
          val dict = js.Dictionary(
            "id" -> idV,
            "images" -> images.toJSArray
          )
          val index = layer.alert(Tool.myElement, Tool.layerOptions)
          val url = "http://localhost:9000/panda/sample/add"
          MyFetch.post(url = s"${url}", data = JSON.stringify(dict), headers = Map("Content-Type" -> "application/json"),
          ).map { xhr =>
            layer.close(index)
            swal(SwalOptions(title = "成功", text = "录入成功!", `type` = "success"))
          }
        }
        ()
      }

      val removeImg = (curI: Int) => {
        val curUris = images.removed(curI)
        setImages(curUris)
      }

      val imagesAdd = (curUris: List[String]) => {
        setImages(images ::: curUris)
      }

      def bootstrapValidator = {
        val formJq = $(formRef.current)
        val url = "http://localhost:9000/panda/sample/idCheck"
        val dict: js.Dictionary[js.Any]  = js.Dictionary(
          "feedbackIcons" -> js.Dictionary(
            "valid" -> "glyphicon glyphicon-ok",
            "invalid" -> "glyphicon glyphicon-remove",
            "validating" -> "glyphicon glyphicon-refresh",
          ),
          "fields" -> js.Dictionary(
            "id" -> {
              val info = "样本编号"
              js.Dictionary(
                "validators" -> js.Dictionary(
                  "notEmpty" -> js.Dictionary(
                    "message" -> s"${info}不能为空！"
                  ),
                  "remote" -> js.Dictionary(
                    "message" -> s"${info}已存在！",
                    "url" -> url,
                    "delay" -> 1000,
                    "type" -> "POST",
                  ),
                )
              )
            },
          )
        )
        formJq.bootstrapValidator(dict)
      }

    }

    useEffect(() => {
      FTool.bootstrapValidator
    }, List()
    )

    CpLayer(title = curPage.titleStr)(
      div(className := "page-content",
        div(className := "row-fluid",
          div(className := "row",
            div(className := "col-md-12 col-sm-12",
              div(className := "portlet light",
                div(className := "portlet-title",
                  div(className := "caption", s"${curPage.titleStr}")
                ),
                div(className := "portlet-body",

                  form(className := "form-horizontal", id := "form", ref := formRef,
                    h4("基本信息"),
                    div(className := "form-group",
                      label(className := "control-label col-sm-2", "样本编号:"),
                      div(className := "col-sm-4",
                        PureInputCp(name = "id", `type` = "text", value = idV, onChange = (v: String) => setIdV(v))
                      )
                    ),

                    div(className := "form-group",
                      label(className := "control-label col-sm-2", "图片:"),
                      div(className := "col-sm-10",
                        ImageSelectCp(images = images, removeImg = FTool.removeImg, imagesAdd = FTool.imagesAdd)
                      )
                    ),

                    div(className := "form-group",
                      div(className := "actions col-sm-offset-2 col-sm-2",
                        button(`type` := "button", className := "btn btn-primary myAddShow", onClick := FTool.add,
                          s" 录入",
                        ),
                      )
                    ),

                  ),

                ),
              )
            )
          )
        )
      )
    )

  }


}
